package com.tth.learn.addproperties.exer;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * @Author tth
 * @Date 2022/12/22 14:59
 */
public class FileTest {

    @Test
    public void test1() {
        File file = new File("d:\\io");
        file.mkdirs();

        file = new File("d:\\io\\io1\\io2");
        file.mkdirs();

        file = new File("d:\\io\\hi.txt");
        try {
            boolean newFile = file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        File file = new File("D:\\project\\study_notes\\java基础\\images\\Java系统学习");

        String[] list = file.list();
        for (String s: list) {
            String[] split = s.split("\\.");
            if (split[split.length-1].equals("png")) {
                System.out.println(s);
            }
        }
        System.out.println("遍历完成");
    }

    @Test
    public void test3() {
        File file = new File("D:\\project\\study_notes");

        int size = fileSize(file, 0);
        System.out.println(size);
    }

    public int fileSize(File file, int size){
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f: files) {
                size = fileSize(f, size);
            }
        } else {
            size += file.length();
        }
        return size;
    }

    @Test
    public void test4() {
        File file = new File("D:\\tmp");
        deleteFile(file);
        System.out.println("文件夹"+file.getPath()+"删除完成");
    }

    public void deleteFile(File file) {
        if (!file.exists()) {
            System.out.println("文件夹不存在！");
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                file.delete();
            } else {
                for (File f: files) {
                    deleteFile(f);
                }
            }
        }


        file.delete();
        System.out.println(file.getName()+"删除成功");
    }
}
